package com.sam.im.heiqun.utils;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.app.App;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.GroupEntivity;
import com.sam.im.heiqun.entities.GroupFriendEntivity;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImGroupEntivity;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.LoginEntivity;
import com.sam.im.heiqun.entities.MsgEntity;
import com.sam.im.heiqun.entities.PhoneUserEntivity;
import com.sam.im.heiqun.entities.ReadyEntivity;
import com.sam.im.heiqun.entities.RedPacketEntivity;
import com.sam.im.heiqun.entities.TipEntity;
import com.sam.im.heiqun.entities.TransferEntivity;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.VoiceEntivity;
import com.sam.im.heiqun.entities.model.LocationEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.activities.AccountActivity;
import com.sam.im.heiqun.uis.activities.ChatActivity;
import com.sam.im.heiqun.uis.activities.ChatGroupActivity;
import com.sam.im.heiqun.uis.activities.LoginActivity;
import com.sam.im.heiqun.uis.activities.MainActivity;
import com.sam.im.heiqun.uis.activities.StartActivity;
import com.sam.im.heiqun.uis.adapters.ChatRecyclerAdapter;
import com.sam.im.heiqun.uis.widgets.sidebar.CharacterParserUtil;
import com.sam.im.heiqun.uis.widgets.sidebar.CountrySortModel;
import com.sam.im.heiqun.uis.widgets.sidebar.GetCountryNameSort;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.utils.data.PrefsUtils;
import com.yuyh.library.utils.data.safe.MD5;
import com.yuyh.library.utils.toast.NotificationUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/**
 * Created by wangguodong on 2017/1/9.
 */
public class ToolsUtils {

    public static Context context;
    public static boolean isConversation = false;



    /**
     * 获取本地登录用户UID，防止空指针
     */
    public static String getMyUserId() {
        ImFriendEntivity m = getUser();
        return null == m ? "32" : "" + m.getId();
    }

    public static CountrySortModel changeFriendEntvity(ImFriendEntivity mImFriendEntivity, CharacterParserUtil characterParserUtil, GetCountryNameSort countryChangeUtil) {

        String name = mImFriendEntivity.getRemark();
        if (null == name || "".equals(name)) {
            name = mImFriendEntivity.getName();
        }
        if (null == name || "".equals(name)) {
            name = "#";
        }

        String countrySortKey = characterParserUtil.getSelling(name);
        String sortLetter = countryChangeUtil.getSortLetterBySortKey(countrySortKey);
        if (sortLetter == null) {
            sortLetter = countryChangeUtil.getSortLetterBySortKey(name);
        }
        CountrySortModel mCountrySortModel = new CountrySortModel(name, countrySortKey).setSortLetters(countryChangeUtil.getSortLetterBySortKey(sortLetter));
        mCountrySortModel.setId(mImFriendEntivity.getId());
        mCountrySortModel.setName(mImFriendEntivity.getName());
        mCountrySortModel.setHeadUrl(mImFriendEntivity.getHeadUrl());
        mCountrySortModel.setReceiveTip(mImFriendEntivity.getReceiveTip());
        mCountrySortModel.setBirthday(mImFriendEntivity.getBirthday());
        mCountrySortModel.setCity(mImFriendEntivity.getCity());
        mCountrySortModel.setCreateTime(mImFriendEntivity.getCreateTime());
        mCountrySortModel.setDetail(mImFriendEntivity.getDetail());
        mCountrySortModel.setDistrict(mImFriendEntivity.getDistrict());
        mCountrySortModel.setIsBlack(mImFriendEntivity.getIsBlack());
        mCountrySortModel.setMail(mImFriendEntivity.getMail());
        mCountrySortModel.setIsOnline(mImFriendEntivity.getIsOnline());
        mCountrySortModel.setMobile(mImFriendEntivity.getMobile());
        mCountrySortModel.setName(mImFriendEntivity.getName());
        mCountrySortModel.setNeedAuth(mImFriendEntivity.getNeedAuth());
        mCountrySortModel.setNewNotification(mImFriendEntivity.getNewNotification());
        mCountrySortModel.setNickName(mImFriendEntivity.getNickName());
        mCountrySortModel.setProvince(mImFriendEntivity.getProvince());
        mCountrySortModel.setPwd(mImFriendEntivity.getPwd());
        mCountrySortModel.setRemark(mImFriendEntivity.getRemark());
        mCountrySortModel.setSearchMobile(mImFriendEntivity.getSearchMobile());
        mCountrySortModel.setSex(mImFriendEntivity.getSex());
        mCountrySortModel.setSign(mImFriendEntivity.getSign());
        mCountrySortModel.setStatus(mImFriendEntivity.getStatus());

        return mCountrySortModel;
    }

    /**
     * 获取昵称
     *
     * @param imFriendEntivity
     * @return
     */
    public static String getNick(ImFriendEntivity imFriendEntivity) {

        if (null == imFriendEntivity) return "";
        if (imFriendEntivity.getRemark() != null && !imFriendEntivity.getRemark().equals("")) {
            return imFriendEntivity.getRemark();
        } else if (imFriendEntivity.getMarkName() != null && !imFriendEntivity.getMarkName().equals("")) {
            return imFriendEntivity.getMarkName();
        } else if (imFriendEntivity.getName() != null && !imFriendEntivity.getName().equals("")) {
            return imFriendEntivity.getName();
        } else if (imFriendEntivity.getNickName() != null && !imFriendEntivity.getNickName().equals("")) {
            return imFriendEntivity.getNickName();
        } else if (imFriendEntivity.getId() != null && !imFriendEntivity.getId().equals("")) {
            return imFriendEntivity.getId() + "";
        }
        return "";
    }

    /**
     * 聊天语音转换
     *
     * @param url
     * @param time
     * @return
     */
    public static String voiceEntivityToStr(String url, float time) {
        VoiceEntivity voiceEntivity = new VoiceEntivity();
        voiceEntivity.setTime(time);
        voiceEntivity.setUrl(url);
        String contentStr = new Gson().toJson(voiceEntivity);
        return contentStr;
    }

    /**
     * 撤回消息转换
     * @return
     */
   /* public static String withdrawToStr(String msgid){
        Map<String,String> map = new HashMap<>();
        map.put("msgid",msgid);
        JsonObject object  = new JsonObject(map);
    }*/

    /**
     * 位置信息转换
     *
     * @param url
     * @param addr
     * @param lat
     * @param lut
     * @return
     */
    public static String locationEntivityToStr(String url, String addr, double lat, double lut) {
        LocationEntivity locationEntivity = new LocationEntivity();
        locationEntivity.setUrl(url);
        locationEntivity.setAddr(addr);
        locationEntivity.setLat(lat);
        locationEntivity.setLut(lut);
        String s = new Gson().toJson(locationEntivity);
        return s;
    }

    /**
     * 群聊查找其中一個群成員
     *
     * @param mFriendEntivities
     * @return
     */
    public static ImFriendEntivity getFriend(List<ImFriendEntivity> mFriendEntivities, String destid) {
        if (mFriendEntivities != null) {
            for (int i = 0; i < mFriendEntivities.size(); i++) {
                ImFriendEntivity imFriendEntivity = mFriendEntivities.get(i);
                if (("" + imFriendEntivity.getId()).equals(destid)) {
                    return imFriendEntivity;
                }
            }
        }
        return null;
    }

    /**
     * 群聊查找其中一個群成員的名称
     *
     * @param mFriendEntivities
     * @return
     */
    public static String getFriendName(List<ImFriendEntivity> mFriendEntivities, String destid) {
        if (mFriendEntivities != null) {
            for (int i = 0; i < mFriendEntivities.size(); i++) {
                ImFriendEntivity imFriendEntivity = mFriendEntivities.get(i);
                if (("" + imFriendEntivity.getId()).equals(destid)) {
                    return getNick(imFriendEntivity);
                }
            }
        }
        return "";
    }

    /**
     * 关闭软件盘
     *
     * @param activity
     * @param mEditText
     */
    public static void closeKeyboard(Activity activity, EditText mEditText) {
        //关闭软键盘
        if (activity.getCurrentFocus() != null) {
            InputMethodManager im = (InputMethodManager) activity.getSystemService(activity.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(activity.getCurrentFocus().getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 延时显示软键盘
     *
     * @param editText
     */
    public static void popupKeyboard(final EditText editText) {

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(editText, 0);
                           }

                       },
                200);
    }

    /**
     * 软件下载，保存本地的文件格式规定，可通过此方法将URL转化为fileName
     *
     * @param urlStr
     * @return
     */
    public static String getPathFileName(String urlStr) {
        String last = urlStr.substring(urlStr.lastIndexOf("."));
        String first = urlStr.substring(0, urlStr.lastIndexOf("."));
        String path = Environment.getExternalStorageDirectory() + "/file/" + MD5.MD516(first) + last;
        Log.i("-----", "getPathFileName: path == " + path);///storage/emulated/0/file/dce6133283769296.amr
        return path;
    }

    /**
     * 保存文件的路径
     *
     * @param urlStr
     * @return
     */
    public static String getFilepathName(String urlStr) {
       /* String last = urlStr.substring(urlStr.lastIndexOf("."));
        String first = urlStr.substring(0, urlStr.lastIndexOf("."));*/
        String[] split = urlStr.split("/");
        String path = Environment.getExternalStorageDirectory() + split[split.length - 1];
        //Log.i("-----", "getPathFileName: path == " + path);///storage/emulated/0/file/dce6133283769296.amr
        return path;
    }

    public static String getRedPacketInfo(String info) {
        RedPacketEntivity mRedPacketEntivity = getRedPacket(info);
        return "" + mRedPacketEntivity.getRedPacketId();
    }

    public static RedPacketEntivity getRedPacket(String info) {
        String newInfo = "";
        String newInfo2 = "";
        if (info.startsWith("\"")) {
            newInfo = info.substring(1);
        } else {
            newInfo = info;
        }
        if (newInfo.endsWith("\"")) {
            newInfo2 = newInfo.substring(0, newInfo.length() - 1);
        } else {
            newInfo2 = newInfo;
        }
        Log.i("-----", "getRedPacketInfo: ---newInfo2=" + newInfo2);
        RedPacketEntivity mRedPacketEntivity = new Gson().fromJson(newInfo2, RedPacketEntivity.class);
        return mRedPacketEntivity;
    }

    public static String getTransferInfo(String info) {
        TransferEntivity mTransferEntivity = getTransfer(info);
        return "" + mTransferEntivity.getTransId();
    }

    public static TransferEntivity getTransfer(String info) {
        String newInfo = "";
        String newInfo2 = "";
        if (info.startsWith("\"")) {
            newInfo = info.substring(1);
        } else {
            newInfo = info;
        }
        if (newInfo.endsWith("\"")) {
            newInfo2 = newInfo.substring(0, newInfo.length() - 1);
        } else {
            newInfo2 = newInfo;
        }
        Log.i("-----", "getTransferEntivityInfo: ---newInfo2=" + newInfo2);
        TransferEntivity mTransferEntivity = new Gson().fromJson(newInfo2, TransferEntivity.class);
        return mTransferEntivity;
    }

    public static String getStrTimeFlong(String time) {
        return getStrTimeFlong(Long.parseLong(time));
    }

    public static String getStrTimeFlong(long time) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sDateFormat.format(new Date(time));
    }

    public static void startAnimal(ImageView mImageView) {
        final float centerX = mImageView.getWidth() / 2.0f;
        final float centerY = mImageView.getHeight() / 2.0f;
        Rotate3dAnimation rotation = new Rotate3dAnimation(0, -360, centerX, centerY, 0.0f,
                false);
        rotation.setDuration(800);
        rotation.setFillAfter(true);
        rotation.setInterpolator(new AccelerateInterpolator());
        // 设置监听
        rotation.setAnimationListener(new DisplayNextView(mImageView));
        mImageView.startAnimation(rotation);
    }

    @Nullable
    public static GroupFriendEntivity getGroupMember(String groupId,String userId) {
        List<GroupFriendEntivity> groupFriendEntivities = GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=? and uid=?",groupId,userId);
        if (null != groupFriendEntivities && groupFriendEntivities.size() > 0) {
            return groupFriendEntivities.get(0);
        }
        return null;
    }

    @Nullable
    public static GroupFriendEntivity getGroupMemberByName(String groupId,String name) {
        List<GroupFriendEntivity> groupFriendEntivities = GroupFriendEntivity.find(GroupFriendEntivity.class,
                "belong_group_id=? and name=?", String.valueOf(groupId), name);
        if (null != groupFriendEntivities && groupFriendEntivities.size() > 0) {
            return groupFriendEntivities.get(0);
        }
        return null;
    }

    public static final class DisplayNextView implements Animation.AnimationListener {
        //
        private ImageView mImageView;

        private DisplayNextView(ImageView mImageView) {
            this.mImageView = mImageView;
        }

        public void onAnimationStart(Animation animation) {
        }

        // 动画结束
        public void onAnimationEnd(Animation animation) {
            startAnimal(mImageView);
        }

        public void onAnimationRepeat(Animation animation) {
        }
    }

    /**
     * 当前网络是否可用
     *
     * @return
     */
    public static boolean currentNetState(Context context) {

        if (App.NET_STATE == Constant.NOT_NET_STATE) {
            Toast.makeText(context, "当前网络连接异常", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            return true;
        }
    }

    public static boolean isMyFriendForId(long uid) {

        ImFriendEntivity myFriendForId = getMyFriendForId(uid);
        return myFriendForId != null && !("0".equals(myFriendForId.getIsFriend()));
    }

    public static ImFriendEntivity getMyFriendForId(long uid) {
        List<ImFriendEntivity> imFriendEntivities = ImFriendEntivity.find(ImFriendEntivity.class, "currentid = ? and id=?", getMyUserId(), uid + "");
        if (imFriendEntivities == null) {
            return null;
        } else {
            if (imFriendEntivities.size() > 0) {
                return imFriendEntivities.get(0);
            } else {
                return null;
            }
        }
    }

    /**
     * 保存本地用户，先清空之前数据
     *
     * @param imFriendEntivity
     * @return
     */
    public static void saveUser(ImFriendEntivity imFriendEntivity, String mobilePrefix, String mobile, String password) {
        List<UserEntivity> userEntivities = UserEntivity.listAll(UserEntivity.class);
        for (int i = 0; i < userEntivities.size(); i++) {
            UserEntivity entivity = userEntivities.get(i);
            entivity.setLoginState(0);
            entivity.save();
        }
        UserEntivity userEntivity = UserEntivity.findById(UserEntivity.class, imFriendEntivity.getId());
        if (userEntivity == null) {
            userEntivity = new UserEntivity();
        }
        userEntivity.setIMNo(imFriendEntivity.getIMNo());
        userEntivity.setLoginState(1);
        userEntivity.setBirthday(imFriendEntivity.getBirthday());
        userEntivity.setCity(imFriendEntivity.getCity());
        userEntivity.setCreateTime(imFriendEntivity.getCreateTime());
        userEntivity.setDetail(imFriendEntivity.getDetail());
        userEntivity.setDistrict(imFriendEntivity.getDistrict());
        userEntivity.setHeadUrl(imFriendEntivity.getHeadUrl());
        userEntivity.setId(imFriendEntivity.getId());
        userEntivity.setIsBlack(imFriendEntivity.getIsBlack());
        userEntivity.setIsOnline(imFriendEntivity.getIsOnline());
        userEntivity.setMail(imFriendEntivity.getMail());
        userEntivity.setMobile(imFriendEntivity.getMobile());
        userEntivity.setName(imFriendEntivity.getName());
        userEntivity.setNeedAuth(imFriendEntivity.getNeedAuth());
        userEntivity.setNewNotification(imFriendEntivity.getNewNotification());
        userEntivity.setNickName(imFriendEntivity.getNickName());
        userEntivity.setRealName(imFriendEntivity.getRealName());
        userEntivity.setReceiveTip(imFriendEntivity.getReceiveTip());
        userEntivity.setRemark(imFriendEntivity.getRemark());
        userEntivity.setSearchMobile(imFriendEntivity.getSearchMobile());
        userEntivity.setSex(imFriendEntivity.getSex());
        userEntivity.setSign(imFriendEntivity.getSign());
        userEntivity.setStatus(imFriendEntivity.getStatus());
        userEntivity.setMobile(mobile);
        userEntivity.setIsAuth(imFriendEntivity.getIsAuth());
        userEntivity.setIdNo(imFriendEntivity.getIdNo());
        userEntivity.setMobilePrefix(mobilePrefix);
        userEntivity.setPassword(password);
        userEntivity.setFeedBackImage(imFriendEntivity.getFeedBackImage());
        userEntivity.save();
    }

    /**
     * 保存好友到本地
     *
     * @param readyEntivity
     * @return
     */
    public static void saveFriendAndGroup(ReadyEntivity readyEntivity) {
        List<UserEntivity> userEntivities = UserEntivity.find(UserEntivity.class, "login_state=?", "1");
        UserEntivity userEntivity;
        if (userEntivities.size() > 0) {
            userEntivity = userEntivities.get(0);
        } else {
            return;
        }
        //更新服务器上的好友数据
        List<ImFriendEntivity> imFriendEntivities = readyEntivity.getAllFriendsInfo();
        ImFriendEntivity.deleteAll(ImFriendEntivity.class);
        for (int i = 0; i < imFriendEntivities.size(); i++) {
            ImFriendEntivity imFriendEntivity = imFriendEntivities.get(i);
            imFriendEntivity.setCurrentid(userEntivity.getId());
            imFriendEntivity.save();
        }
        //更新服务器上的群组数据
        List<ImGroupEntivity> imGroupEntivities = readyEntivity.getGroupsInfo();
        ImGroupEntivity.deleteAll(ImGroupEntivity.class,"currentid != ?",ToolsUtils.getMyUserId());
        for (int i = 0; i < imGroupEntivities.size(); i++) {
            ImGroupEntivity imGroupEntivity = imGroupEntivities.get(i);
            imGroupEntivity.setCurrentid(userEntivity.getId());
            if (imGroupEntivity.getMarkName() == null || imGroupEntivity.getMarkName().equals("")) {
                String markName = getGroupMemberNick(readyEntivity.getMyInfo());
                imGroupEntivity.setMarkName(markName);
            }
            imGroupEntivity.save();
        }
        EventBus.getDefault().post(Constant.BLACK_BROADCAST_FOUND_REFRESH);
    }

    /**
     * 获取群成员昵称
     *
     * @param imFriendEntivity
     * @return
     */
    public static String getGroupMemberNick(ImFriendEntivity imFriendEntivity) {

        if (imFriendEntivity.getMarkName() != null && !imFriendEntivity.getMarkName().equals("")) {
            return imFriendEntivity.getMarkName();
        } else if (imFriendEntivity.getName() != null && !imFriendEntivity.getName().equals("")) {
            return imFriendEntivity.getName();
        } else if (imFriendEntivity.getNickName() != null && !imFriendEntivity.getNickName().equals("")) {
            return imFriendEntivity.getNickName();
        } else if (imFriendEntivity.getId() != null && !imFriendEntivity.getId().equals("")) {
            return imFriendEntivity.getId() + "";
        }
        return "";
    }

    /**
     * 保存好友到本地
     *
     * @param destid
     * @return
     */
    public static ImFriendEntivity getFriendById(String destid) {
        UserEntivity userEntivity = getUser();
        ImFriendEntivity imFriendEntivity = null;
        if (userEntivity != null) {
            List<ImFriendEntivity> imFriendEntivities = ImFriendEntivity.find(ImFriendEntivity.class, "currentid = ?", userEntivity.getId() + "");

            for (int i = 0; i < imFriendEntivities.size(); i++) {
                if ((destid + "").equals(imFriendEntivities.get(i).getId() + "")) {
                    imFriendEntivity = imFriendEntivities.get(i);
                    break;
                }
            }
        }
        return imFriendEntivity;
    }

    /**
     * 通过ID获取好友备注名
     *
     * @param destid
     * @return
     */
    public static String getFriendRemarkName(String destid) {
        ImFriendEntivity imFriendEntivity = getFriendById(destid);
        if (null != imFriendEntivity && null != imFriendEntivity.getRemark() && !"".equals(imFriendEntivity.getRemark())) {
            return imFriendEntivity.getRemark();
        }
        return "";
    }

    /**
     * 获取个人信息
     *
     * @return
     */
    public static UserEntivity getUser() {

//        if (App.userEntivity == null) {
        List<UserEntivity> userEntivities = UserEntivity.find(UserEntivity.class, "login_state=?", "1");
        if (userEntivities.size() > 0) {
            App.userEntivity = userEntivities.get(0);
            return userEntivities.get(0);
        }
        return null;
//        } else {
//            return App.userEntivity;
//        }
    }

    public static String getGroupUserName(List<ImFriendEntivity> imFriendEntivities, long uid) {
        if (null == imFriendEntivities || imFriendEntivities.size() == 0) {
            return App.getInstance().getString(R.string.have_people);
        } else {
            for (int i = 0; i < imFriendEntivities.size(); i++) {
                if (("" + uid).equals(imFriendEntivities.get(i).getId())) {
                    return imFriendEntivities.get(i).getName();
                }
            }
            return App.getInstance().getString(R.string.have_people);
        }
    }

    /**
     * 聊天消息通知
     *
     * @param imMessage
     * @param content
     */
    public static void notification(ImMessage imMessage, String content) {
        String showTile = "";
        int id = 0;
        //  Log.i("-----", "notification: imMessage.getDestid()=" + imMessage.getFromid() + "" + imMessage.getFromid());
        //获取系统是否需要开启通知
        String newNotificationM = new PrefsUtils(App.getInstance(), Constant.NEW_NOTIFICTION).get(Constant.NEW_NOTIFICTION, "");
        if (newNotificationM.equals(Constant.AGREE_ADD_FRIEND_N)) {
            // Log.i("info","系统不需要通知");
            return;
        }
        if (imMessage.getType() == ChatRecyclerAdapter.FROM_USER_EMOJI || imMessage.getType() == ChatRecyclerAdapter.FROM_USER_EMOJI_TEXT) {
            MsgEntity msgEntity = new Gson().fromJson(content, MsgEntity.class);
            String msgString = msgEntity.getMsgString();
            showTile = msgString;
        }
        // Log.i("info","收到系统通知");
        if ((App.destid + "").equals("-1")) {//不在单聊和群聊界面
            Intent intent = new Intent(App.getInstance().getApplicationContext(), ChatActivity.class);
            if (imMessage.getFromType() == Constant.FROM_TYPE_MAM) {
                intent = new Intent(App.getInstance().getApplicationContext(), ChatActivity.class);
                intent.putExtra("destid", imMessage.getDestid());
                id = imMessage.getDestid().intValue();
            } else if (imMessage.getFromType() == Constant.FROM_TYPE_GROUP) {
                intent = new Intent(App.getInstance().getApplicationContext(), ChatGroupActivity.class);
                intent.putExtra("groupid", imMessage.getFromid());
                id = imMessage.getFromid().intValue();
            } else if (imMessage.getFromType() == Constant.FROM_TYPE_SYS) {//系统通知
                intent = new Intent(App.getInstance().getApplicationContext(), MainActivity.class);//接收到系统通知跳转到首页
                intent.putExtra("int", 1);
            }

            ImFriendEntivity imFriendEntivity = ImFriendEntivity.findById(ImFriendEntivity.class, imMessage.getDestid());
            String title = "";
            title = imMessage.getFromname() + "";
           /* if (imFriendEntivity != null) {
                title = ToolsUtils.getNick(imFriendEntivity);
            } else {
                title = imMessage.getDestid() + "";
            }*/

            if (imMessage.getFromType() == Constant.FROM_TYPE_SYS) {
                if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_APPLY_FRIEND || imMessage.getMessageType() == Constant.NOTICE_OF_APPLY_FRIEND) {
                    NotificationUtils.notification(App.getInstance().getApplicationContext(), intent, id, R.mipmap.ic_launcher, "", title, "请求加您为好友");
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_TRANSFOR_ISCOME) {
                    intent = new Intent(App.getInstance().getApplicationContext(), AccountActivity.class);
                    NotificationUtils.notification(App.getInstance().getApplicationContext(), intent, id, R.mipmap.ic_launcher, "", "黑群支付", "您有一笔款项到账");
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_TOPAYFOR) {
                    intent = new Intent(App.getInstance().getApplicationContext(), AccountActivity.class);
                    NotificationUtils.notification(App.getInstance().getApplicationContext(), intent, id, R.mipmap.ic_launcher, "", "黑群支付", "您有一笔款项支付成功");
                }
            } else {
                if (showTile.equals("")) return;
                NotificationUtils.notification(App.getInstance().getApplicationContext(), intent, id, R.mipmap.ic_launcher, "", title, showTile);
            }
        } else {
            Intent intent = new Intent(App.getInstance().getApplicationContext(), ChatActivity.class);
            if (imMessage.getFromType() == Constant.FROM_TYPE_MAM) {
                intent = new Intent(App.getInstance().getApplicationContext(), ChatActivity.class);
                intent.putExtra("destid", imMessage.getDestid());
                id = imMessage.getDestid().intValue();
                if (imMessage.getFromType() == Constant.FROM_TYPE_MAM && (App.destid + "").equals(id + "")) {//是当前聊天界面就不提示
                    return;
                }
            } else if (imMessage.getFromType() == Constant.FROM_TYPE_GROUP) {
                intent = new Intent(App.getInstance().getApplicationContext(), ChatGroupActivity.class);
                intent.putExtra("groupid", imMessage.getFromid());
                id = imMessage.getFromid().intValue();
                if (imMessage.getFromType() == Constant.FROM_TYPE_GROUP && (App.destid + "").equals(id + "")) {//是当前聊天界面就不提示
                    return;
                }
            } else if (imMessage.getFromType() == Constant.FROM_TYPE_SYS) {//系统通知
                intent = new Intent(App.getInstance().getApplicationContext(), MainActivity.class);//接收到系统通知跳转到首页
                intent.putExtra("typetag", Constant.MESSAGE_TYPR_APPLY_FRIEND);

            }
            ImFriendEntivity imFriendEntivity = ImFriendEntivity.findById(ImFriendEntivity.class, imMessage.getDestid());
            String title = "";
            if (imMessage.getFromType() == Constant.FROM_TYPE_SYS) {
                title = "系统消息";
            } else {
                title = imMessage.getFromname();
            }
          /*  if (imFriendEntivity != null) {
                title = ToolsUtils.getNick(imFriendEntivity);
            } else {
                title = imMessage.getDestid() + "";
            }*/
            if (imMessage.getFromType() == Constant.FROM_TYPE_SYS) {
                if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_APPLY_FRIEND || imMessage.getMessageType() == Constant.MESSAGE_TYPR_APPLY_FRIEND) {
                    NotificationUtils.notification(App.getInstance().getApplicationContext(), intent, id, R.mipmap.ic_launcher, "", title, "请求加您为好友");
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_TRANSFOR_ISCOME) {
                    NotificationUtils.notification(App.getInstance().getApplicationContext(), intent, id, R.mipmap.ic_launcher, "", "黑群支付", "您有一笔款项到账");
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_TOPAYFOR) {
                    NotificationUtils.notification(App.getInstance().getApplicationContext(), intent, id, R.mipmap.ic_launcher, "", "黑群支付", "您有一笔款项支付成功");
                }
            }
        }
    }

    /**
     * 获取翻译的支持语言
     */
    public static HashMap<String, String> getMyFanYiMap() {
        HashMap<String, String> myMap = new HashMap<>();
        myMap.put("zhCN", "zh");
        myMap.put("zhHK", "zh");
        myMap.put("en", "en");
//        myMap.put("+852","yue");
        myMap.put("ja", "jp");
        myMap.put("ko", "kor");
        myMap.put("fr", "fra");
        myMap.put("es", "spa");
        myMap.put("th", "th");
        myMap.put("ar", "ara");
        myMap.put("ru", "ru");
        myMap.put("pt", "pt");
        myMap.put("de", "de");
        myMap.put("it", "it");
        myMap.put("el", "el");
        myMap.put("nl", "nl");
        myMap.put("pl", "pl");
        myMap.put("bg", "bul");
        myMap.put("et", "est");
        myMap.put("da", "dan");
        myMap.put("fi", "fin");
        myMap.put("cs", "cs");
        myMap.put("ro", "rom");
        myMap.put("sl", "slo");
        myMap.put("sv", "swe");
        myMap.put("hu", "hu");
        myMap.put("zhTW", "cht");
        myMap.put("vi", "vie");
        return myMap;
    }

    public static String getTimeString(long time) {
        int h = (int) (time / 3600);
        int m = (int) ((time % 3600) / 60);
        int s = (int) ((time % 3600) % 60);
        String mtime = h > 0 ? (m > 0 ? (s > 0 ? h + "时" + m + "分" + s + "秒" : h + "时" + m + "分") : h + "时") : (m > 0 ? (s > 0 ? m + "分" + s + "秒" : m + "分") : s + "秒");
        return mtime;
    }

    public static List<ImFriendEntivity> getWFriendsInfo() {
        List<ImFriendEntivity> imFriendEntivities = ImFriendEntivity.find(ImFriendEntivity.class, "currentid = ? and is_black=?", new String[]{getUser().getId() + "", "0"});
        return imFriendEntivities;
    }

    public static List<ImFriendEntivity> getBFriendsInfo() {
        List<ImFriendEntivity> imFriendEntivities = ImFriendEntivity.find(ImFriendEntivity.class, "currentid = ? and is_black=?", new String[]{getUser().getId() + "", "1"});
        return imFriendEntivities;
    }

    public static void fileIsDelete() {
        File f = null;
        try {
            f = new File(Environment.getExternalStorageDirectory() + "chatSend.png");
            if (!f.exists()) {
                return;
            }
        } catch (Exception e) {
            // TODO: handle exception
            return;
        }
        if (null != f) f.delete();
    }


    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    /**
     * * Checks if the app has permission to write to device storage
     * *
     * * If the app does not has permission then the user will be prompted to
     * * grant permissions
     * *
     * * @param activity
     */
    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static String getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 拼接PHP所用的接口Uid
     *
     * @return 9872a39e423e07f3578780085fc9028f
     */
    public static String getPhpUid() {
        String str = "9872a39e423e07f3578780085fc9028f" + getMyUserId();
        return new String(Base64.encode(str.getBytes(), Base64.DEFAULT));
    }


    /**
     * 保存查询到的群组成员列表
     *
     * @param imFriendEntivities
     * @param groupId
     */
    public static void saveGroupUserS(List<ImFriendEntivity> imFriendEntivities, long groupId) {
        if (null != imFriendEntivities && imFriendEntivities.size() > 0) {
            List<GroupFriendEntivity> mFriendEntivities = ToolsUtils.getGroupUserSss(groupId);
            int iSize = mFriendEntivities.size();
            if (null == mFriendEntivities || iSize <= 0) {
                for (int i = 0; i < imFriendEntivities.size(); i++) {
                    GroupFriendEntivity mm = new GroupFriendEntivity(imFriendEntivities.get(i));
                    mm.setBelongGroupId(groupId);
                    mm.save();
                }
            } else {
                boolean isHave = false;
                long id = 0;
                GroupFriendEntivity mm = null;
                for (int j = 0; j < imFriendEntivities.size(); j++) {
                    ImFriendEntivity imFriendEntivity = imFriendEntivities.get(j);
                    for (int i = 0; i < iSize; i++) {
                        Log.i("-----", "saveGroupUserS: 保存群成员，本地getUid=" + mFriendEntivities.get(i).getUid() + "获取到getId=" + imFriendEntivity.getUserId());
                        if (("" + mFriendEntivities.get(i).getUid()).equals("" + imFriendEntivity.getUserId())) {
                            mm = mFriendEntivities.get(i);
                            mm.setName(imFriendEntivity.getName());
                            mm.setUid(imFriendEntivity.getUserId());
                            mm.setSilence(imFriendEntivity.getSilence());
                            mm.setRole(imFriendEntivity.getRole());
                            mm.setExpire(imFriendEntivity.getExpire());
                            mm.setJoinWay(imFriendEntivity.getJoinWay());
                            isHave = true;
                            id = mFriendEntivities.get(i).getId();
                        }
                    }
                    if (isHave) {
                        mm.setBelongGroupId(groupId);
                        mm.setId(id);
                        isHave = false;
                    } else {
                        mm = new GroupFriendEntivity(imFriendEntivity);
                        mm.setBelongGroupId(groupId);
                    }
                    if (null != mm) mm.save();
                }

                for (int i = 0; i < iSize; i++) {
                    int size = imFriendEntivities.size();
                    GroupFriendEntivity groupFriendEntivity = mFriendEntivities.get(i);
                    for (int j = 0; j < size; j++) {
                        String uid = groupFriendEntivity.getUid() + "";
                        if ((imFriendEntivities.get(j).getId() + "").equals(uid)) {
                            isHave = true;
                        }
                    }
                    if (!isHave) {
                        groupFriendEntivity.delete();
                    } else {
                        isHave = false;
                    }
                }
            }
        }
    }

    /**
     * 保存查询到的群组成员-d单个
     *
     * @param imFriendEntivitie
     * @param groupId
     */
    public static void saveGroupUser(ImFriendEntivity imFriendEntivitie, long groupId) {
        if (null != imFriendEntivitie) {
            GroupFriendEntivity mm = new GroupFriendEntivity(imFriendEntivitie);
            mm.setBelongGroupId(groupId);
            mm.save();
        }
    }

    /**
     * 删除群组成员-d单个
     *
     * @param imFriendEntivitie
     * @param groupId
     */
    public static void deleteGroupUser(ImFriendEntivity imFriendEntivitie, long groupId) {
        if (null != imFriendEntivitie) {
            GroupFriendEntivity mm = new GroupFriendEntivity(imFriendEntivitie);
            mm.setBelongGroupId(groupId);
            mm.delete();
        }
    }

    /**
     * 查询本地群组成员列表-- 分页
     *
     * @param groupId
     */
    public static List<ImFriendEntivity> getGroupUserS(String groupId, int start) {
        List<ImFriendEntivity> imFriendEntivities = new ArrayList<>();
        List<GroupFriendEntivity> groupFriendEntivities = GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=?", new String[]{"" + groupId}, "", "", start + ",20");

        if (null != groupFriendEntivities && groupFriendEntivities.size() > 0) {
            for (int i = 0; i < groupFriendEntivities.size(); i++) {
                imFriendEntivities.add(groupFriendEntivities.get(i).getImFriend());
            }
        }
        return imFriendEntivities;
    }

    /**
     * 查询本地群组成员列表 -- 所有
     *
     * @return
     */
    public static List<ImFriendEntivity> getAllGroupUeaer(String groupId) {
        List<ImFriendEntivity> imFriendEntivities = new ArrayList<>();
        List<GroupFriendEntivity> groupFriendEntivities = ToolsUtils.groupUserRemoval(GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=?", "" + groupId));
        if (null != groupFriendEntivities && groupFriendEntivities.size() > 0) {
            for (int i = 0; i < groupFriendEntivities.size(); i++) {
                imFriendEntivities.add(groupFriendEntivities.get(i).getImFriend());
            }
        }
        return imFriendEntivities;
    }

    /**
     * 查询本地群组成员列表 -- 除去我
     *
     * @return
     */
    public static List<ImFriendEntivity> getOutMeGroupUeaer(String groupId) {
        List<ImFriendEntivity> imFriendEntivities = new ArrayList<>();
        List<GroupFriendEntivity> groupFriendEntivities = ToolsUtils.groupUserRemoval(GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=?", "" + groupId));
        if (null != groupFriendEntivities && groupFriendEntivities.size() > 0) {
            for (int i = 0; i < groupFriendEntivities.size(); i++) {
                if (!("" + groupFriendEntivities.get(i).getImFriend().getUserId()).equals(getMyUserId()))
                    imFriendEntivities.add(groupFriendEntivities.get(i).getImFriend());
            }
        }
        return imFriendEntivities;
    }

    /**
     * 查询本地群组成员列表
     *
     * @param groupId
     */
    public static List<GroupFriendEntivity> getGroupUserSss(long groupId) {
        List<GroupFriendEntivity> groupFriendEntivities = GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=?", "" + groupId);

        return groupFriendEntivities;
    }

    public static String getRealPathFromURI(Uri contentUri, Context context) {
        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        if (cursor.moveToFirst()) {
            ;
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
        }
        cursor.close();
        return res;
    }

    /**
     * 保存readyEntivity
     *
     * @param readyEntivity
     * @param mobile
     * @param password
     * @param loginEntivity
     */
    public void saveReadyEntivity(ReadyEntivity readyEntivity, String mobilePrefix, String mobile, String password, LoginEntivity loginEntivity) {
        try {
            ImFriendEntivity imFriendEntivity = readyEntivity.getMyInfo();
            List<TipEntity> tipEntities = readyEntivity.getTopList();
            for (int i = 0; i < tipEntities.size(); i++) {
                TipEntity tipEntity = tipEntities.get(i);
                List<TipEntity> tipEntities1 = TipEntity.find(TipEntity.class, "dest_id=? and user_id=?", tipEntity.getDestId(), tipEntity.getUserId());
                if (tipEntities1.size() == 0) {
                    tipEntity.save();
                }
            }
            ToolsUtils.saveUser(imFriendEntivity, mobilePrefix, mobile, password);
            ToolsUtils.saveFriendAndGroup(readyEntivity);


            //----- 获取payInfo，
            String payInfo = readyEntivity.getPayInfo();
            if (payInfo != null && !payInfo.equals("")) {
                UserEntivity user = ToolsUtils.getUser();
                user.setPayInfo(payInfo);
                ImFriendEntivity.save(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * ready
     */
    public static void ready(final PGService mPgService, final String mobileCode, final String mobile, final String password, final LoginEntivity loginEntivity, final Activity activity) {
        Log.i(TAG, "ready: ===============loginEntivity.getToken()=" + loginEntivity.getToken());
        //1010e3d28a13881c96acb

        Observable.just(loginEntivity)
                .map(new Function<LoginEntivity, LoginEntivity>() {
                    @Override
                    public LoginEntivity apply(LoginEntivity loginEntivity) throws Exception {

                        App.imIpAfterReady = loginEntivity.getImServerUrl();
                        App.tokenAfterReady = loginEntivity.getToken();
                        App.isManualLogout = false;
                        App.phone = mobile;

                        savesocketstr(App.getInstance(), loginEntivity.getImServerUrl(), loginEntivity.getToken(), 1);

                        return loginEntivity;
                    }
                })
                .compose(RxJavaUtil.<LoginEntivity>applySchedules())
                .flatMap(new Function<LoginEntivity, ObservableSource<ReadyEntivity>>() {
                    @Override
                    public ObservableSource<ReadyEntivity> apply(final LoginEntivity loginEntivity) throws Exception {

                        return PGService.getInstance().ready(loginEntivity.getToken())
                                .doOnNext(new Consumer<ReadyEntivity>() {
                                    @Override
                                    public void accept(ReadyEntivity readyEntivity) throws Exception {
                                        new ToolsUtils().saveReadyEntivity(readyEntivity, mobileCode, mobile, password, loginEntivity);
                                    }
                                })
                                .compose(RxJavaUtil.<ReadyEntivity>applySchedules());
                    }
                })
                .subscribe(new AbsAPICallback<ReadyEntivity>() {
                    @Override
                    public void onNext(final ReadyEntivity readyEntivity) {//成功后连接长连接
                        Log.i("ToolsUtils", "ready====IMNo==" + readyEntivity.getMyInfo().getIMNo());

                        if (activity != null) {
                            if (activity instanceof LoginActivity) {
                                ((LoginActivity) activity).startActivity(MainActivity.class);
                                activity.finish();
                            } else if (activity instanceof StartActivity) {
                                Intent intent = new Intent(activity, MainActivity.class);
                                activity.startActivity(intent);
                                activity.finish();
                            }
                        }
                    }

                    @Override
                    protected void onResultError(ApiException ex) {
                        // Log.e(TAG, "onResultError:  登录进去，但是并没有获取 ready 实体！！！！");
                        doLogin(mPgService, mobileCode, activity, mobile, password);
                    }
                });
    }

    public static boolean isDoLogin = false;
    private static final String TAG = "ToolsUtils";

    /**
     * 登陆
     */
    public static void doLogin(final PGService mPgService, final String mobileCode, final Activity activity, final String mobile, final String pwd) {
        Log.i(TAG, "doLogin: -------01-------=");
        if (activity instanceof LoginActivity) {
            Log.i(TAG, "doLogin: -------02-------=");
            if (!ToolsUtils.currentNetState(activity)) {
                return;
            }
            Log.i(TAG, "doLogin: -------03-------=");
            ((LoginActivity) activity).showProgress(activity.getResources().getString(R.string.logining_please_wait));
        }
        Log.i(TAG, "doLogin: -------04-------=");
        final String password;
        if (pwd.length() > 20) {
            password = pwd;
        } else {
            password = MD5.MD532(pwd);
        }

        //int current = Integer.parseInt(ToolsUtils.getVersion(activity));
        mPgService.doLogin(mobileCode + mobile, password, GetDeviceid.id(ToolsUtils.context)).subscribe(new AbsAPICallback<LoginEntivity>() {
            @Override
            public void onNext(LoginEntivity loginEntivity) {//登录成功后，保存用户信息

                isDoLogin = true;
//   http://123.57.47.19:8080/wmsMobile/chat/doLogin?mobile=+8615265923720&pwd=e10adc3949ba59abbe56e057f20f883e&device=1
                App.loginUrl = "http://" + loginEntivity.getImServerUrl() + "/wms/";//设置地址
                Log.i(TAG, "onNext: -----------------------App.loginUrl--" + App.loginUrl);
                ToolsUtils.ready(mPgService, mobileCode, mobile, pwd, loginEntivity, activity);
                ToolsUtils.saveLoginstate(activity, true, 1);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                Log.i(TAG, "onNext: ---------登录接口失败---doLogin-----onError------App.loginUrl--" + App.loginUrl);
                //showToast((LoginActivity)activity,"网络连接失败，请稍后再试");
            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.i(TAG, "onNext: ---------登录接口失败---doLogin-----onResultError------App.loginUrl--" + App.loginUrl);
                if (activity instanceof LoginActivity) {
                    ((LoginActivity) activity).hideProgress();
                    switch (ex.getCode()) {
                        case 2:
                            showToast((LoginActivity) activity, activity.getResources().getString(R.string.user_name_nonenitity));
                            // ((LoginActivity) activity).showToast(activity.getResources().getString(R.string.user_name_nonenitity));
                            break;
                        case 3:
                            showToast((LoginActivity) activity, activity.getResources().getString(R.string.psd_error));
                            // ((LoginActivity) activity).showToast(activity.getResources().getString(R.string.psd_error));
                            break;
                        case 4:
                            showToast((LoginActivity) activity, activity.getResources().getString(R.string.has_been_frozen));
                            // ((LoginActivity) activity).showToast(activity.getResources().getString(R.string.psd_error));
                            break;
                        default:
                            ((LoginActivity) activity).showToast(activity.getResources().getString(R.string.net_busy_please_wait_try));
                            break;
                    }
                } else if (activity instanceof MainActivity) {

                    //showToast((LoginActivity) activity, activity.getResources().getString(R.string.net_Login_failure));
                    //循环登陆
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                if (isDoLogin) {
                                    return;
                                }
                                Thread.sleep(2000);
//                                EventBus.getDefault().post(Constant.NOT_NET_SERVICE);
                                doLogin(mPgService, mobileCode, activity, mobile, pwd);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                        }
                    }).start();

                } else if (activity instanceof StartActivity) {
                    Intent intent = new Intent(activity, LoginActivity.class);
                    activity.startActivity(intent);
                    activity.finish();
                }
            }
        });
    }

    public static String getMac() {
        String macSerial = null;
        String str = "";
        try {
            Process pp = Runtime.getRuntime().exec(
                    "cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);


            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (IOException ex) {
            // 赋予默认值
            macSerial = "0";
            ex.printStackTrace();
        }
        return macSerial;
    }

    /**
     * 判断是否是手机号码
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {

        boolean b = mobiles.length() == 11;
        return b;

    }

    //判断是否是手机号
    public static boolean isMobile(String mobiles) {
    /*
    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、180、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
    */
        String telRegex = "[1][3578]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }

    //判断是否为json字符串
    public static boolean isGoodJson(String json) {

        try {
            new JsonParser().parse(json);
            return true;
        } catch (JsonParseException e) {
            System.out.println("bad json: " + json);
            return false;
        }
    }

    //打开文件的方法
    public static Intent openFile(String filePath) {

        File file = new File(filePath);
        if (!file.exists()) return null;
        /* 取得扩展名 */
        String end = file.getName().substring(file.getName().lastIndexOf(".") + 1, file.getName().length()).toLowerCase();
        /* 依扩展名的类型决定MimeType */
        if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") ||
                end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            return getAudioFileIntent(filePath);
        } else if (end.equals("3gp") || end.equals("mp4")) {
            return getVideoFileIntent(filePath);
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png") ||
                end.equals("jpeg") || end.equals("bmp")) {
            return getImageFileIntent(filePath);
        } else if (end.equals("apk")) {
            return getApkFileIntent(filePath);
        } else if (end.equals("ppt")) {
            return getPptFileIntent(filePath);
        } else if (end.equals("xls")) {
            return getExcelFileIntent(filePath);
        } else if (end.equals("doc")) {
            return getWordFileIntent(filePath);
        } else if (end.equals("pdf")) {
            return getPdfFileIntent(filePath);
        } else if (end.equals("chm")) {
            return getChmFileIntent(filePath);
        } else if (end.equals("txt")) {
            return getTextFileIntent(filePath, false);
//        } else if (end.equals("apk")) {
//            return getAllIntent(filePath);
        } else {
            return null;
        }
    }

    //Android获取一个用于打开APK文件的intent
    public static Intent getAllIntent(String param) {

        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "*/*");
        return intent;
    }

    //Android获取一个用于打开APK文件的intent
    public static Intent getApkFileIntent(String param) {

        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        return intent;
    }

    //Android获取一个用于打开VIDEO文件的intent
    public static Intent getVideoFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("oneshot", 0);
        intent.putExtra("configchange", 0);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "video/*");
        return intent;
    }

    //Android获取一个用于打开AUDIO文件的intent
    public static Intent getAudioFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("oneshot", 0);
        intent.putExtra("configchange", 0);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "audio/*");
        return intent;
    }

    //Android获取一个用于打开Html文件的intent
    public static Intent getHtmlFileIntent(String param) {

        Uri uri = Uri.parse(param).buildUpon().encodedAuthority("com.android.htmlfileprovider").scheme("content").encodedPath(param).build();
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.setDataAndType(uri, "text/html");
        return intent;
    }

    //Android获取一个用于打开图片文件的intent
    public static Intent getImageFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "image/*");
        return intent;
    }

    //Android获取一个用于打开PPT文件的intent
    public static Intent getPptFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
        return intent;
    }

    //Android获取一个用于打开Excel文件的intent
    public static Intent getExcelFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "application/vnd.ms-excel");
        return intent;
    }

    //Android获取一个用于打开Word文件的intent
    public static Intent getWordFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "application/msword");
        return intent;
    }

    //Android获取一个用于打开CHM文件的intent
    public static Intent getChmFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "application/x-chm");
        return intent;
    }

    //Android获取一个用于打开文本文件的intent
    public static Intent getTextFileIntent(String param, boolean paramBoolean) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (paramBoolean) {
            Uri uri1 = Uri.parse(param);
            intent.setDataAndType(uri1, "text/plain");
        } else {
            Uri uri2 = Uri.fromFile(new File(param));
            intent.setDataAndType(uri2, "text/plain");
        }
        return intent;
    }

    //Android获取一个用于打开PDF文件的intent
    public static Intent getPdfFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "application/pdf");
        return intent;
    }

    //转换uri
    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    //传入文件下载链接判断文件是否已经在本地存在
    public static boolean isExsite(String url) {
        String[] split = url.split("/");
        String filename = split[split.length - 1];
        String SDCard = Environment.getExternalStorageDirectory() + File.separator;
        //pathName = ToolsUtils.getFilepathName(urlStr);//文件存储路径
        // Log.i("info","pathname=="+pathName);
        String pathName = SDCard + "easyfile" + File.separator + filename;
        try {
            File file = new File(pathName);
            if (!file.exists()) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }

        return true;
    }
   /* public static boolean isDebug = true;// 是否需要打印bug，可以在application的onCreate函数里面初始化
    private static final String TAG = "way";
    public static void e(String msg)
    {
        if (isDebug)
            Log.e(TAG, msg);
    }
    */

    /**
     * 分段打印出较长log文本
     *
     * @param
     * @param （AndroidStudio控制台打印log的最大信息量大小为4k）
     * @param
     *//*
    public static void showLargeLog(String logContent, int showLength, String tag){
        if(logContent.length() > showLength){
            String show = logContent.substring(0, showLength);
            Log.d(tag,show);
            *//*剩余的字符串如果大于规定显示的长度，截取剩余字符串进行递归，否则打印结果*//*
            if((logContent.length() - showLength) > showLength){
                String partLog = logContent.substring(showLength,logContent.length());
                showLargeLog(partLog, showLength, tag);
            }else{
                String printLog = logContent.substring(showLength, logContent.length());
                Log.d(tag,printLog);
            }

        }else{
            Log.d(tag,logContent);
        }
    }*/
    //存动态未读状态
    public static void saveCirclenums(Context context, boolean isread) {
        SharedPreferences mySharePreferences = context.getSharedPreferences("myshare", Activity.MODE_PRIVATE);
        //实例化SharedPreferences.Editor对象
        SharedPreferences.Editor editor = mySharePreferences.edit();
        editor.putBoolean("read", isread);
        editor.commit();
    }

    //取动态未读状态
    public static boolean getCirclenums(Context context) {
        SharedPreferences mySharePreferences = context.getSharedPreferences("myshare", Activity.MODE_PRIVATE);
        return mySharePreferences.getBoolean("read", false);
    }

    /**
     * 缓存
     */
    public static void saveSf(Context context, HashMap<String, String> map) {
        //实例化SharedPreferences对象,参数1是存储文件的名称，参数2是文件的打开方式，当文件不存在时，直接创建，如果存在，则直接使用
        SharedPreferences mySharePreferences = context.getSharedPreferences("myshare", Activity.MODE_PRIVATE);
        //实例化SharedPreferences.Editor对象
        SharedPreferences.Editor editor = mySharePreferences.edit();
        Set set = map.keySet();
        Iterator iter = set.iterator();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            editor.putString(key, map.get(key));
        }
        iter.remove();
        //提交数据
        editor.commit();
    }

    /**
     * 保存raedy链接参数
     */
    public static String savesocketstr(Context context, String imurl, String imtoken, int type) {//1  为存  2  为取
        SharedPreferences mySharePreferences = context.getSharedPreferences("myshare", Activity.MODE_PRIVATE);
        //实例化SharedPreferences.Editor对象
        SharedPreferences.Editor editor = mySharePreferences.edit();
        if (type == 1) {
            editor.putString("imurl", imurl);
            editor.putString("imtoken", imtoken);
            editor.commit();
            return "";
        } else {
            return mySharePreferences.getString("imurl", "") + "___" + mySharePreferences.getString("imtoken", "");
        }
    }

    /**
     * 保存用户设置看一看
     */
    public static String saveLook(Context context, String userid, String isshow, int type) {//1  为存  2  为取
        SharedPreferences mySharePreferences = context.getSharedPreferences("myshare", Activity.MODE_PRIVATE);
        //实例化SharedPreferences.Editor对象
        SharedPreferences.Editor editor = mySharePreferences.edit();
        if (type == 1) {
            editor.putString("userid", userid);
            editor.putString("isshowlook", isshow);
            editor.commit();
            return "";
        } else {
            if (userid.equals(mySharePreferences.getString("userid", ""))) {
                return mySharePreferences.getString("isshowlook", "0");
            } else {
                return "0";
            }

        }
    }

    /**
     * 保存用户设置看一看
     */
    public static String saveSearch(Context context, String userid, String isshow, int type) {//1  为存  2  为取
        SharedPreferences mySharePreferences = context.getSharedPreferences("myshare", Activity.MODE_PRIVATE);
        //实例化SharedPreferences.Editor对象
        SharedPreferences.Editor editor = mySharePreferences.edit();
        if (type == 1) {
            editor.putString("userid", userid);
            editor.putString("isshowsearch", isshow);
            editor.commit();
            return "";
        } else {
            if (userid.equals(mySharePreferences.getString("userid", ""))) {
                return mySharePreferences.getString("isshowsearch", "0");
            } else {
                return "0";
            }

        }
    }

    /**
     * 保存多语言设置
     */
    public static String saveLanguage(Context context, String language, int type) {//1  为存  2  为取
        SharedPreferences mySharePreferences = context.getSharedPreferences("myshare", Activity.MODE_PRIVATE);
        //实例化SharedPreferences.Editor对象
        SharedPreferences.Editor editor = mySharePreferences.edit();
        if (type == 1) {
            editor.putString("language", language);
            editor.commit();
            return "";
        } else {
            return mySharePreferences.getString("language", "zh_cn");

        }
    }

    /**
     * 保存登录状态
     */
    public static boolean saveLoginstate(Context context, boolean islogin, int type) {//1  为存  2  为取
        SharedPreferences mySharePreferences = context.getSharedPreferences("myshare", Activity.MODE_PRIVATE);
        //实例化SharedPreferences.Editor对象
        SharedPreferences.Editor editor = mySharePreferences.edit();
        if (type == 1) {
            editor.putBoolean("login", islogin);
            editor.commit();
            return false;
        } else {
            return mySharePreferences.getBoolean("login", false);
        }
    }

    /**
     * 从缓存中提取
     */
    public static String getSf(Context context, String key) {
        SharedPreferences share = context.getSharedPreferences("myshare",
                Activity.MODE_PRIVATE);
        return share.getString(key, "");
    }

    //吐司单例
    private static String oldMsg;
    protected static Toast toast = null;
    private static long oneTime = 0;
    private static long twoTime = 0;

    public static void showToast(Context context, String s) {
        if (toast == null) {
            toast = Toast.makeText(context.getApplicationContext(), s, Toast.LENGTH_SHORT);
            toast.show();
            oneTime = System.currentTimeMillis();
        } else {
            twoTime = System.currentTimeMillis();
            if (s.equals(oldMsg)) {
                if (twoTime - oneTime > Toast.LENGTH_SHORT) {
                    toast.show();
                }
            } else {
                oldMsg = s;
                toast.setText(s);
                toast.show();
            }
        }
        oneTime = twoTime;
    }

    private static final double EARTH_RADIUS = 6378137.0;

    public static double getDistance(double longitude1, double latitude1,
                                     double longitude2, double latitude2) {

        double Lat1 = rad(latitude1);
        double Lat2 = rad(latitude2);
        double a = Lat1 - Lat2;
        double b = rad(longitude1) - rad(longitude2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(Lat1) * Math.cos(Lat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    //切图
    public static void cropImageUri(Activity context, Uri uri, int outputX, int outputY, int requestCode) {

        Intent intent = new Intent("com.android.camera.action.CROP");

        intent.setDataAndType(uri, "image/*");

        intent.putExtra("crop", "true");

//        intent.putExtra("aspectX", 2);
        intent.putExtra("aspectX", outputX);

//        intent.putExtra("aspectY", 2);
        intent.putExtra("aspectY", outputY);

        intent.putExtra("outputX", outputX);

        intent.putExtra("outputY", outputY);

        intent.putExtra("scale", true);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

        intent.putExtra("return-data", false);

        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        intent.putExtra("noFaceDetection", true); // no face detection

        context.startActivityForResult(intent, requestCode);

    }

    /**
     * 相对路径转绝对路径
     *
     * @param selectedVideoUri
     * @param contentResolver
     * @return
     */
    public static String getFilePathFromContentUri(Uri selectedVideoUri,
                                                   ContentResolver contentResolver) {
        String filePath;
        String[] filePathColumn = {MediaStore.MediaColumns.DATA};

        Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
//      也可用下面的方法拿到cursor
//      Cursor cursor = this.context.managedQuery(selectedVideoUri, filePathColumn, null, null, null);

        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        filePath = cursor.getString(columnIndex);
        cursor.close();
        return filePath;
    }

    public static ImMessage getTbub(int version, int devType, int geoId, int type,
                                    String msgId, long fromId, int fromType,
                                    long destId, String content, int messageType,
                                    long sendTime, long receiveTime, int status, String filePath, String uniqueness, float seconds, String imageIconUrl) {
        ImMessage tbub = new ImMessage();
        tbub.setVersion(version);
        tbub.setDevType(devType);
        tbub.setUserVoiceTime(seconds);
        tbub.setType(type);
        tbub.setGeoId(geoId);
        tbub.setMsgId(msgId);
        tbub.setFromid(fromId);
        tbub.setFromType(fromType);
        tbub.setFileUrl(filePath);
        tbub.setFilePath(filePath);
        //tbub.setUserVoicePath(content);
        tbub.setDestid(destId);
        if ("null".equals(content)) {
            content = "null ";
        }
        tbub.setContent(content);
        tbub.setMessageType(messageType);
        tbub.setFromname(ToolsUtils.getUser().getNickName());//设置名字
        tbub.setSendTime(sendTime);
        tbub.setReceiveTime(receiveTime);
        tbub.setStatus(status);
        tbub.setUniqueness(uniqueness);
        tbub.setSendState(Constant.SENDING);
        tbub.setImageIconUrl(imageIconUrl);
        return tbub;
    }

    /**
     * 联系人显示名称
     **/
    private static final int PHONES_DISPLAY_NAME_INDEX = 0;
    /**
     * 电话号码
     **/
    private static final int PHONES_NUMBER_INDEX = 1;
    /**
     * 头像ID
     **/
    private static final int PHONES_PHOTO_ID_INDEX = 2;
    /**
     * 联系人的ID
     **/
    private static final int PHONES_CONTACT_ID_INDEX = 3;

    /**
     * 分页查询系统联系人信息
     *
     * @param pageSize      每页最大的数目
     * @param currentOffset 当前的偏移量
     * @return
     */
    public static List<PhoneUserEntivity> getContactsByPage(final ContentResolver resolver, Context mContext, int pageSize, int currentOffset) {
        List<PhoneUserEntivity> infos = new ArrayList<>();
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String[] projection = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER,
                ContactsContract.CommonDataKinds.Photo.PHOTO_ID,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
//                "_id"
        };//COLLATE LOCALIZED"name = ?".""
        //"name like '%?%' or phone like '%?%'"
        Cursor phoneCursor = resolver.query(uri, projection, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " asc limit " + pageSize + " offset " + currentOffset);
        if (phoneCursor != null) {//_id
            while (phoneCursor.moveToNext()) {
                //得到手机号码
                String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
                //当手机号码为空的或者为空字段 跳过当前循环
                if (TextUtils.isEmpty(phoneNumber))
                    continue;
                //得到联系人名称
                String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);
                //得到联系人ID
                Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID_INDEX);
                //得到联系人头像ID
                Long photoid = phoneCursor.getLong(PHONES_PHOTO_ID_INDEX);
//                //得到联系人头像Bitamp
                Bitmap contactPhoto = null;
                //photoid 大于0 表示联系人有头像 如果没有给此人设置头像则给他一个默认的
                if (photoid > 0) {
                    Uri urip = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactid);
                    InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(resolver, urip);
                    contactPhoto = BitmapFactory.decodeStream(input);
                } else {
                    contactPhoto = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.register_person);
                }
                PhoneUserEntivity model = new PhoneUserEntivity();
                model.setName(contactName);
                model.setNumber(phoneNumber);
                model.setPhone(contactPhoto);
//                LinkmenModel model = new LinkmenModel("", "", null);
                infos.add(model);
                model = null;
            }
            phoneCursor.close();
        }
        return infos;
    }

    //在一定范围内生成随机数.
    //比如此处要求在[0 - n)内生成随机数.
    //注意:包含0不包含n
    public static String getRandom() {
        Random random = new Random();
        return "" + (random.nextInt(8999) + 1000);
    }

    public static File saveImageToGallery(Bitmap bmp,File saveDir) {
        // 首先保存图片
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(saveDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

//    // 返回单位是米
//    public static double getDistance(double longitude1, double latitude1,
//                                     double longitude2, double latitude2) {
//        double Lat1 = rad(latitude1);
//        double Lat2 = rad(latitude2);
//        double a = Lat1 - Lat2;
//        double b = rad(longitude1) - rad(longitude2);
//        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
//                + Math.cos(Lat1) * Math.cos(Lat2)
//                * Math.pow(Math.sin(b / 2), 2)));
//        s = s * EARTH_RADIUS;
//        s = Math.round(s * 10000) / 10000;
//        return s;
//    }
//
//    public static double rad(double d) {
//        return d * Math.PI / 180.0;
//    }

    public static int getGroupRole(String groupid) {
        return getGroupRole(groupid, getMyUserId());
    }

    public static int getGroupRole(String groupid, String uid) {
        List<GroupFriendEntivity> groupFriendEntivities2 = GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=? and uid=?", new String[]{groupid, uid});
        int role = 3;
        if (null != groupFriendEntivities2 && groupFriendEntivities2.size() > 0) {
            if ("1".equals(groupFriendEntivities2.get(0).getRole())) {
                role = 1;
            } else if ("2".equals(groupFriendEntivities2.get(0).getRole())) {
                role = 2;
            }
        }
        return role;
    }

    //    public static List<GroupFriendEntivity> groupUserRemovalRemove(List<GroupFriendEntivity> groupFriendEntivities){
//        try {
//            List<GroupFriendEntivity> mGroupFriendEntivities = new ArrayList<>();
//            if (null!=groupFriendEntivities && groupFriendEntivities.size() > 0){
//                for (int i = 0; i < groupFriendEntivities.size(); i++) {
//                    if (null!=groupFriendEntivities && groupFriendEntivities.size() > 0 && null!=mGroupFriendEntivity){
//                        for (int j = 0; j < groupFriendEntivities.size(); j++) {
//                            if ((""+mGroupFriendEntivity.getUid()).equals(""+groupFriendEntivities.get(i).getUid()) && pos > i){
//                                return true;
//                            }
//                        }
//                    }
//                }
//            }
//            return mGroupFriendEntivities ;
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return groupFriendEntivities;
//    }
//    private static boolean isGroupUserRemovalRemove(List<GroupFriendEntivity> groupFriendEntivities, GroupFriendEntivity mGroupFriendEntivity, int pos){
//        try {
//            if (null!=groupFriendEntivities && groupFriendEntivities.size() > 0 && null!=mGroupFriendEntivity){
//                for (int i = 0; i < groupFriendEntivities.size(); i++) {
//                    if ((""+mGroupFriendEntivity.getUid()).equals(""+groupFriendEntivities.get(i).getUid()) && pos > i){
//                        return true;
//                    }
//                }
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return false;
//    }
    public static List<GroupFriendEntivity> groupUserRemoval(List<GroupFriendEntivity> groupFriendEntivities) {
        try {
            List<GroupFriendEntivity> mGroupFriendEntivities = new ArrayList<>();
            if (null != groupFriendEntivities && groupFriendEntivities.size() > 0) {
                for (int i = 0; i < groupFriendEntivities.size(); i++) {
                    if (isGroupUserRemoval(groupFriendEntivities, groupFriendEntivities.get(i), i)) {
                        //这个是重复的
                        continue;
                    }
                    mGroupFriendEntivities.add(groupFriendEntivities.get(i));
                }
            }
            return mGroupFriendEntivities;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return groupFriendEntivities;
    }

    private static boolean isGroupUserRemoval(List<GroupFriendEntivity> groupFriendEntivities, GroupFriendEntivity mGroupFriendEntivity, int pos) {
        try {
            if (null != groupFriendEntivities && groupFriendEntivities.size() > 0 && null != mGroupFriendEntivity) {
                for (int i = 0; i < groupFriendEntivities.size(); i++) {

                    if (("" + mGroupFriendEntivity.getId()).equals("" + groupFriendEntivities.get(i).getId()) && pos > i) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static List<ImFriendEntivity> gUserRemoval(List<ImFriendEntivity> groupFriendEntivities) {
        try {
            List<ImFriendEntivity> mGroupFriendEntivities = new ArrayList<>();
            if (null != groupFriendEntivities && groupFriendEntivities.size() > 0) {
                for (int i = 0; i < groupFriendEntivities.size(); i++) {
                    if (isUserRemoval(groupFriendEntivities, groupFriendEntivities.get(i), i)) {
                        //这个是重复的
                        continue;
                    }
                    mGroupFriendEntivities.add(groupFriendEntivities.get(i));
                }
            }
            return mGroupFriendEntivities;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return groupFriendEntivities;
    }

    private static boolean isUserRemoval(List<ImFriendEntivity> groupFriendEntivities, ImFriendEntivity mGroupFriendEntivity, int pos) {
        try {
            if (null != groupFriendEntivities && groupFriendEntivities.size() > 0 && null != mGroupFriendEntivity) {
                for (int i = 0; i < groupFriendEntivities.size(); i++) {
                    if (("" + mGroupFriendEntivity.getId()).equals("" + groupFriendEntivities.get(i).getId()) && pos > i) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static List<CountrySortModel> gCountrySortModelRemoval(List<CountrySortModel> groupFriendEntivities) {
        try {
            List<CountrySortModel> mGroupFriendEntivities = new ArrayList<>();
            if (null != groupFriendEntivities && groupFriendEntivities.size() > 0) {
                for (int i = 0; i < groupFriendEntivities.size(); i++) {
                    Log.i(TAG, "gCountrySortModelRemoval: ===================================" + groupFriendEntivities.get(i).getUserId());
                    if (isCountrySortModelRemoval(groupFriendEntivities, groupFriendEntivities.get(i), i)) {
                        //这个是重复的
                        continue;
                    }
                    mGroupFriendEntivities.add(groupFriendEntivities.get(i));
                }
            }
            groupFriendEntivities.clear();
            groupFriendEntivities.addAll(mGroupFriendEntivities);
            return groupFriendEntivities;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return groupFriendEntivities;
    }

    private static boolean isCountrySortModelRemoval(List<CountrySortModel> groupFriendEntivities, CountrySortModel mGroupFriendEntivity, int pos) {
        try {
            if (null != groupFriendEntivities && groupFriendEntivities.size() > 0 && null != mGroupFriendEntivity) {
                for (int i = 0; i < groupFriendEntivities.size(); i++) {
//                    if ((""+mGroupFriendEntivity.getUserId()).equals(""+groupFriendEntivities.get(i).getUserId()) && pos > i){
                    if (("" + mGroupFriendEntivity.getId()).equals("" + groupFriendEntivities.get(i).getId()) && pos > i) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 获取剩余禁言时间
     *
     * @return
     */
    public static long getLastAnExcuseTime(String groupId, String userId) {

//        mGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, id);
//        return mGroupEntivity != null && "1".equals(mGroupEntivity.getSilence());

        List<GroupFriendEntivity> groupFriendEntivities = GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=? and uid=?", groupId, userId);
        if (null != groupFriendEntivities && groupFriendEntivities.size() > 0) {
            GroupFriendEntivity groupFriendEntivity = groupFriendEntivities.get(0);
            if (!TextUtils.isEmpty(groupFriendEntivity.getSilence())) {
                long anExcuseTime = Long.parseLong(groupFriendEntivity.getSilence());
                return anExcuseTime - System.currentTimeMillis();
            }
        }
        return -1;
    }

    /**
     * 是否被全体禁言
     *
     * @return
     */
    public static boolean isAnExcuseAllGroupMember(long groupId) {


        int groupRole = getGroupRole(String.valueOf(groupId));
        if (groupRole == 1||groupRole == 2) {
            return false;
        }
        ImGroupEntivity groupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, groupId);
        return groupEntivity != null && "1".equals(groupEntivity.getSilenceP());
    }

    /**
     * 获取群管理员变更描述
     *
     * @param imMessage
     * @return
     */
    public static String getManagerChangeTxt(Context context,ImMessage imMessage, boolean setManager) {

        JSONObject jsonObject = JSON.parseObject(imMessage.getContent());
        String name = jsonObject.getString("name");
        if (com.sam.im.heiqun.utils.StringUtils.isEmpty(name)) {
            name = context.getResources().getString(R.string.have_people);
        }
        List<GroupFriendEntivity> groupFriendEntivities3 = GroupFriendEntivity.find(GroupFriendEntivity.class,
                "belong_group_id=? and name=?", "" + imMessage.getFromid(), name);
        if (null != groupFriendEntivities3 && groupFriendEntivities3.size() > 0 && getMyUserId().equals(String.valueOf(groupFriendEntivities3.get(0).getUid()))) {
            return setManager ? context.getString(R.string.you_has_bean_set_manager)
                    : context.getString(R.string.you_has_bean_not_manager);
        } else {
            return setManager ? name + context.getString(R.string.has_bean_set_manager)
                    : name + context.getString(R.string.has_bean_set_not_manager);
        }
    }
    /**
     * 随机生产文件名
     *
     * @return
     */
    private static String generateFileName() {
        return UUID.randomUUID().toString();
    }
    /**
     * 保存bitmap到本地
     *
     * @param context
     * @param mBitmap
     * @return
     */
    public static String saveBitmapToSdCard(Context context, Bitmap mBitmap,String path) {
        String savePath;
        File filePic;
        /*if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            savePath = SD_PATH;
        } else {
            savePath = context.getApplicationContext().getFilesDir()
                    .getAbsolutePath()
                    + IN_PATH;
        }*/
        try {
            filePic = new File(path);
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        return filePic.getAbsolutePath();
    }

    /**
     * 创建一条图片地址uri,用于保存拍照后的照片
     *
     * @param context
     * @return 图片的uri
     */
    public static Uri createImagePathUri(Context context) {
        Uri imageFilePath = null;
        String status = Environment.getExternalStorageState();
        SimpleDateFormat timeFormatter = new SimpleDateFormat(
                "yyyyMMdd_HHmmss", Locale.CHINA);
        long time = System.currentTimeMillis();
        String imageName = timeFormatter.format(new Date(time));
        // ContentValues是我们希望这条记录被创建时包含的数据信息
        ContentValues values = new ContentValues(3);
        values.put(MediaStore.Images.Media.DISPLAY_NAME, imageName);
        values.put(MediaStore.Images.Media.DATE_TAKEN, time);
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
        if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
            imageFilePath = context.getContentResolver().insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        } else {
            imageFilePath = context.getContentResolver().insert(
                    MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
        }
        Log.i("", "生成的照片输出路径：" + imageFilePath.toString());
        return imageFilePath;
    }

    public static File getFileByUri(Uri uri,Context context) {
        String path = null;
        if ("file".equals(uri.getScheme())) {
            path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = context.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=").append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA }, buff.toString(), null, null);
                int index = 0;
                int dataIdx = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    index = cur.getInt(index);
                    dataIdx = cur.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    path = cur.getString(dataIdx);
                }
                cur.close();
                if (index == 0) {
                } else {
                    Uri u = Uri.parse("content://media/external/images/media/" + index);
                    System.out.println("temp uri is :" + u);
                }
            }
            if (path != null) {
                return new File(path);
            }
        } else if ("content".equals(uri.getScheme())) {
// 4.2.2以后
            String[] proj = { MediaStore.Images.Media.DATA };
            Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                path = cursor.getString(columnIndex);
            }
            cursor.close();
            return new File(path);
        } else {
//Log.i(TAG, "Uri Scheme:" + uri.getScheme());
        }
        return null;
    }


    public static final long MIN_STORAGE=52428800;//50*1024*1024最低50m

    /**
     * 递归
     * */
    public static long getFileSize(File f) {
        long size = 0;
        //File flist[] = f.listFiles();
        /*for (int i = 0; i < f.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSize(flist[i]);
            } else {
                size = size + flist[i].length();
            }
        }*/
        return f.length();


    }



}
